//
//  SN_HomeViewController.m
//  Shiyun_Newspaper
//
//  Created by Sylar on 2017/6/5.
//  Copyright © 2017年 ShiYun. All rights reserved.
//

#import "SN_HomeViewController.h"
#import "SNSearchBar.h"
#import "SN_NewspaperModel.h"
#import "SN_Readlist_Model.h"
#import "SN_ReadListCell.h"
#import "SN_SearchViewController.h"
#import "SN_ReadRecordViewController.h"
#import "SN_QuestionReadMoreNews_Controller.h"
#import "SN_NewspaperInfoViewController.h"
#import "SY_Activity.h"
#import "SY_Activity_Model.h"
#import "SN_WebViewController.h"
#import "ScanImageViewController.h"

#import <CoreLocation/CoreLocation.h>

@interface SN_HomeViewController ()<UITableViewDelegate,UITableViewDataSource,UISearchBarDelegate,ReadListDelegate,ScanImageView,CLLocationManagerDelegate>
{
    dispatch_group_t group;
    
    NSTimer *advImgtimer;
    BOOL canFireTimer;
    
    NSString *editionType;
    NSString *gradersId;
    NSString *editionName;
    NSString *graderName;
    
    NSString *defaultGrader;
    NSString *defaultEdition;
    
    NSInteger defaultSelectedEditionIndex;
    NSInteger selectedEditionIndex;
    NSInteger selectedGradeIndex;
    
    UILabel *emptyLable;
    
}

@property (nonatomic, strong) UIButton *subjectBtn;
@property (nonatomic, strong) UIButton *scanBtn;
@property (nonatomic, strong) SNSearchBar *snSearch;
@property (nonatomic, strong) UIControl *control;

@property (nonatomic, strong) UITableView *sel_edition;
@property (nonatomic, strong) UITableView *sel_grader;

@property (nonatomic, strong) UIScrollView *baseScrollView;

@property (nonatomic, strong) UIScrollView *advScrollView;//banner
@property (nonatomic, assign) BOOL advImageLoadSuccess;
@property (nonatomic, strong) UIImageView *pldImageView;
@property (nonatomic, strong) NSArray *advImageArray;
@property (nonatomic, strong) UIPageControl *advPageControl;
@property (nonatomic, strong) UITableView *readListTable;

@property (nonatomic, strong) NSMutableArray *graderArr;
@property (nonatomic, strong) NSMutableArray *editionArr;
@property (nonatomic, strong) NSMutableArray *newspaperArr;

@property (nonatomic, strong) CLLocationManager *locMgr;

@end

@implementation SN_HomeViewController

- (instancetype)init {
    
    if (self == [super init]) {
        self.hidesBottomBarWhenPushed = NO;
    }
    
    return self;
}

- (void)loadView {
    [super loadView];
    
    [self.view setBackgroundColor:colorFromHex(@"ffffff")];
    
    selectedEditionIndex = 0;
    defaultSelectedEditionIndex = 0;
    
    editionType = [SYAccountTool ShareAccount].account.edtiontype;
    gradersId = [SYAccountTool ShareAccount].account.grader;
    graderName = [SYAccountTool ShareAccount].account.gradername;
    editionName = [SYAccountTool ShareAccount].account.edtiontypename;
    defaultGrader = graderName;
    defaultEdition = editionName;
    
    NSString *subStr = [NSString stringWithFormat:@"%@ · %@",[SYAccountTool ShareAccount].account.edtiontypename,[SYAccountTool ShareAccount].account.gradername];
    
    [self.subjectBtn setTitle:subStr forState:(UIControlStateNormal)];
    
    self.snSearch.hidden = NO;
    
}

- (void)viewDidAppear:(BOOL)animated{
    
    [super viewDidAppear:animated];
    
    [advImgtimer invalidate];
    advImgtimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(switchAdvImg) userInfo:nil repeats:YES];
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:YES];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.operationQueue cancelAllOperations];
    
    [advImgtimer invalidate];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //接收广告页消失的通知，此时开启轮播，避免轮播第一张图片显示时间太短
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(advimageDisapper) name:@"advimageDisapper" object:nil];
    
    [self.view addSubview:self.baseScrollView];
    [self.baseScrollView addSubview:self.advScrollView];
    [self.advScrollView addSubview:self.pldImageView];//加载动画
    
    emptyLable = [[UILabel alloc]initWithFrame:CGRectMake(0, 300, SCREENWIDTH, 16)];
    [emptyLable setFont:[UIFont systemFontOfSize:16]];
    [emptyLable setText:@"暂无数据。"];
    [emptyLable setTextColor:colorFromHex(@"979797")];
    [emptyLable setTextAlignment:NSTextAlignmentCenter];
    emptyLable.hidden = YES;
    [self.baseScrollView addSubview:emptyLable];
    
    UIButton *recordBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
    [recordBtn setFrame:CGRectMake(0, self.advScrollView.bottom, SCREENWIDTH, 44)];
    [recordBtn addTarget:self action:@selector(moreRecord) forControlEvents:(UIControlEventTouchUpInside)];
    [recordBtn setBackgroundColor:[UIColor whiteColor]];
    
    [self.baseScrollView addSubview:recordBtn];
    
    UILabel *recLabel = [[UILabel alloc]initWithFrame:CGRectMake(15, self.advScrollView.bottom+14, 100, 16)];
    [recLabel setFont:[UIFont systemFontOfSize:16]];
    [recLabel setText:@"阅读记录"];
    [recLabel setTextColor:colorFromHex(@"#3b3b3b")];
    [self.baseScrollView addSubview:recLabel];
    
    UIImageView *arrImg = [[UIImageView alloc]initWithFrame:CGRectMake(SCREENWIDTH - 15 - 8, 0, 8, 13)];
    arrImg.centerY = recLabel.centerY;
    [arrImg setImage:[UIImage imageNamed:@"more_Record"]];
    [self.baseScrollView addSubview:arrImg];
    
    UIView *lineView = [[UIView alloc]initWithFrame:CGRectMake(0, recordBtn.bottom, SCREENWIDTH, 10)];
    [lineView setBackgroundColor:colorFromHex(@"f4f5f7")];
    [self.baseScrollView addSubview:lineView];
    
    self.readListTable.y = recordBtn.bottom + 10;
    [self.baseScrollView addSubview:self.readListTable];
    
    
    [[DBUtil shareInstance] getEditionAndGradeData:^(NSError *error, NSDictionary *editionInfo, NSDictionary *gradeInfo) {
       
        self.graderArr = [gradeInfo objectForKey:@"re_data"];
        self.editionArr = [editionInfo objectForKey:@"re_data"];
        
        for (int i = 0; i < self.editionArr.count; i++) {
            
            if ([editionName isEqualToString:[[self.editionArr objectAtIndex:i] objectForKey:@"editiontypename"]]) {
                defaultSelectedEditionIndex = i;
                selectedEditionIndex = i;
                break;
            }
        }
    }];
    
    [self getNewspaperData];
    [self loadAdvImage];
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    NSDictionary *notiDict = delegate.notiDict;
    
    if (notiDict) {
        
        NSDictionary *dict = [notiDict objectForKey:@"UIApplicationLaunchOptionsRemoteNotificationKey"];
        
        NSString *infoidStr = [NSString stringWithFormat:@"%@",[dict objectForKey:@"infoid"]];
        NSInteger moveto = [[dict objectForKey:@"moveto"] integerValue];
        
        SY_Activity_Model *model = [[SY_Activity_Model alloc] init];
        model.url = [dict objectForKey:@"url"];
        model.infoid = infoidStr;
        model.moveto = moveto;
        model.apptype = 2;
        
        
        [SY_Activity shareActivity].instructionArr = @[model];
        [[SY_Activity shareActivity] action];
        delegate.notiDict = nil;
    }
    
    //获取定位
    [self getUserLocation];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appdidComeBackToForeGround:) name:UIApplicationDidBecomeActiveNotification object:nil];
}

-(void)dealloc {
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -Notification
- (void)advimageDisapper{
    
    [advImgtimer invalidate];
    canFireTimer = YES;
    
    [self performSelector:@selector(startTimer) withObject:nil afterDelay:4];
}

- (void)startTimer{
    
    [advImgtimer invalidate];
    advImgtimer = [NSTimer scheduledTimerWithTimeInterval:4 target:self selector:@selector(switchAdvImg) userInfo:nil repeats:YES];
}

//回到前台 重新发送下位置信息
- (void)appdidComeBackToForeGround:(NSNotification *)noti {
    
    [_locMgr startUpdatingLocation];
}


#pragma mark - Method

- (void)switchAdvImg{
    
    if (self.advImageArray.count > 1) {
        
        [UIView animateWithDuration:0.3 animations:^{
            
            CGPoint offSet = self.advScrollView.contentOffset;
            
            offSet.x += SCREENWIDTH;
            
            self.advScrollView.contentOffset = offSet;
            
        }];
        
        [self scrollViewDidEndDecelerating:self.advScrollView];
        
    }
}

- (void)getUserLocation {
    
    _locMgr = [[CLLocationManager alloc] init];
    _locMgr.delegate = self;
    _locMgr.distanceFilter = 0.1;
    _locMgr.desiredAccuracy = kCLLocationAccuracyBest;
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];
    
    if (status == kCLAuthorizationStatusNotDetermined) { //还未决定定位权限
        
        [_locMgr requestWhenInUseAuthorization];
    }else if (status == kCLAuthorizationStatusDenied) { //拒绝定位权限
        
        //经纬度传0
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        
        [dict setObject:@"api_user_log" forKey:@"method"];
        [dict setObject:@(0) forKey:@"lat"];
        [dict setObject:@(0) forKey:@"lng"];
        [dict setObject:USERID forKey:@"userid"];
        
        [Utils getWithparameters:dict showHUD:NO success:^(NSInteger recode, id jsonObject) {
            
            
            
        } failure:^(NSInteger recode, NSError *error) {
            
            
        }];
        
    }else if (status == kCLAuthorizationStatusAuthorizedWhenInUse | status == kCLAuthorizationStatusAuthorizedAlways) {
        
        [_locMgr startUpdatingLocation];
    }
}

#pragma mark -CLLocationManagerDelegate

//获取授权状态
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            
            if ([_locMgr respondsToSelector:@selector(requestWhenInUseAuthorization)]) {
                
                [_locMgr requestWhenInUseAuthorization];
            }
            
            break;
        case kCLAuthorizationStatusAuthorizedAlways:
            
            [_locMgr startUpdatingLocation];
            break;
            
        case kCLAuthorizationStatusAuthorizedWhenInUse:
            
            [_locMgr startUpdatingLocation];
            break;
    
        default:
            break;
    }
}


//获取到位置信息
- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    
    CLLocation *loc = [locations firstObject];
    
    CLLocationCoordinate2D cor2d = [loc coordinate];
    
    CLLocationDegrees lat = cor2d.latitude;
    CLLocationDegrees lon = cor2d.longitude;
    
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    
    [dict setObject:@"api_user_log" forKey:@"method"];
    [dict setObject:@(lat) forKey:@"lat"];
    [dict setObject:@(lon) forKey:@"lng"];
    [dict setObject:USERID forKey:@"userid"];
    
    [Utils getWithparameters:dict showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        [manager stopUpdatingLocation];
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [manager stopUpdatingLocation];
    }];
    
    
}



#pragma mark - Action

- (void)scanAction {
    
    NSLog(@"扫一扫");
    ScanImageViewController *scan = [[ScanImageViewController alloc] init];
    //scan.delegate = self;
    scan.type=1;
    [self.navigationController pushViewController:scan animated:YES];
}

- (void)moreRecord {
    
    NSLog(@"阅读记录");
    SN_ReadRecordViewController *recordVC = [[SN_ReadRecordViewController alloc]init];
    [self.navigationController pushViewController:recordVC animated:YES];
}

- (void)advAction:(UIGestureRecognizer *)tap {
    
    UIImageView *imageView = (UIImageView *)tap.view;
    NSInteger index = imageView.tag;
    
    NSDictionary *dic = [self.advImageArray objectAtIndex:index];
    
    NSInteger moveto = [[dic objectForKey:@"logotype"] integerValue];
    
    if (moveto > 0) {
        
        SY_Activity_Model *model = [[SY_Activity_Model alloc]init];
        model.apptype = 2;
        model.infoid = [NSString stringWithFormat:@"%@",[dic objectForKey:@"infoid"]];
        model.moveto = moveto;
        model.url = [dic objectForKey:@"url"];
        
        [SY_Activity shareActivity].instructionArr = @[model];
        [[SY_Activity shareActivity] action];
        return;
    }
    
    
//    NSString *voteUrlStr = [dic objectForKey:@"url"];
//
//    SN_WebViewController *webVC = [[SN_WebViewController alloc] init];
//    webVC.url = voteUrlStr;
//    
//    [self.navigationController pushViewController:webVC animated:YES];
    
}

- (void)selectSubject {
    
    self.subjectBtn.selected = !self.subjectBtn.selected;
    
    if (_control) {
        [self hideControl];
    }else {
        
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2-0.5, 40*self.editionArr.count, 0.5, 40*(9-self.editionArr.count))];
        [line setBackgroundColor:colorFromHex(@"#DEDEDE")];
        [self.sel_edition addSubview:line];
        [self.control addSubview:self.sel_edition];
        [self.control addSubview:self.sel_grader];
        
        [self.view addSubview:self.control];
    }
    
}

- (void)hideControl {
    
    self.subjectBtn.selected = NO;
    [self.control removeFromSuperview];
    self.control = nil;
    self.sel_grader = nil;
    self.sel_edition = nil;
    
    defaultGrader = graderName;
    defaultEdition = editionName;
    
    defaultSelectedEditionIndex = selectedEditionIndex;
}

#pragma mark - Request

- (void)getNavSourceData {
    
    [Utils showHUD];
    
    group = dispatch_group_create();
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        //执行异步任务1
        [self getGraderData];
    });
    
    dispatch_group_enter(group);
    dispatch_group_async(group, queue, ^{
        // 执行异步任务2
        [self getVersionData];
    });
    
    dispatch_group_notify(group, dispatch_get_main_queue(), ^{
        
//        NSString *subStr = [NSString stringWithFormat:@"%@-%@",[[self.classesArr objectAtIndex:0] objectForKey:@"gradername"],[[self.versionArr objectAtIndex:0] objectForKey:@"editiontypename"]];
//        
//        [self.subjectBtn setTitle:subStr forState:(UIControlStateNormal)];
        
        [Utils hideHUD];
        
    });
}

- (void)getGraderData {
    
    
    NSMutableDictionary *param = [[NSMutableDictionary alloc]init];
    
    [param setObject:@"api_classgraders_search" forKey:@"method"];
    
    [Utils getWithparameters:param showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = (NSDictionary *)jsonObject;
        
        self.graderArr = [dic objectForKey:@"re_data"];
        
        
        dispatch_group_leave(group);
        
    } failure:^(NSInteger recode, NSError *error) {
        dispatch_group_leave(group);
    }];
    
}

- (void)getVersionData {
    
    NSMutableDictionary *dict = [[NSMutableDictionary alloc]init];
    
    [dict setObject:@"api_editiontype_list" forKey:@"method"];
    
    [Utils getWithparameters:dict showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = (NSDictionary *)jsonObject;
        
        self.editionArr = [dic objectForKey:@"re_data"];
        
        dispatch_group_leave(group);
        
    } failure:^(NSInteger recode, NSError *error) {
        
        dispatch_group_leave(group);
    }];
}

//加载广告图片
- (void)loadAdvImage{
    
    NSMutableDictionary * dict = [[NSMutableDictionary alloc] initWithCapacity:0];
    [dict setObject:@"api_startpic_list" forKey:@"method"];
    [dict setObject:@"4" forKey:@"type"];
    if (USERID) {
        
        [dict setObject:USERID forKey:@"userid"];
    }
    
    __weak SN_HomeViewController *VC = self;
    
    [Utils getWithparameters:dict showHUD:NO success:^(NSInteger recode, id jsonObject) {

        NSDictionary * dic = (NSDictionary *)jsonObject;
        
        NSMutableArray * dataArr = [[NSMutableArray alloc]initWithArray:[dic objectForKey:@"re_data"]];
        self.advImageArray = dataArr;
        
        if (dataArr.count == 0) {
            
            UIImage *image = [UIImage imageNamed:@"defaut_banner"];
            
            UIImageView *view = [[UIImageView alloc] initWithImage:image];
            
            view.frame = self.advScrollView.bounds;
            view.image = image;
            view.contentMode = UIViewContentModeScaleAspectFit;
            view.frame = self.advScrollView.bounds;
            
            [self.advScrollView addSubview:view];
            
            return;
        }
        
        //这些判断是防止只有一张图片的时候出现滑屏
        int num = 0;
        float x_offset = 0;
        if (dataArr.count > 1) {
            
            num = 2;
            x_offset = SCREENWIDTH;
        }
        
        self.advScrollView.contentSize = CGSizeMake((num + dataArr.count) * self.advScrollView.frame.size.width, 140);
        self.advScrollView.contentOffset = CGPointMake(x_offset, 0);
        
        for (UIView *view in self.advScrollView.subviews) {
            [view removeFromSuperview];
        }
        
        for (int i = 0; i < (dataArr.count > 1 ?  dataArr.count + 2 : dataArr.count); i++) {
            
            NSDictionary *logoDic;
            UIImageView *imageView = [[UIImageView alloc] init];
            
            if (i == 0) {  //第一张
                
                logoDic = [dataArr objectAtIndex:dataArr.count - 1];
                
            }else if(i == dataArr.count + 1){ //最后一张
                
                logoDic = [dataArr objectAtIndex:0];
                
            }else{
                
                logoDic = [dataArr objectAtIndex:i - 1];
            }
            
            NSString * pic = [logoDic objectForKey:@"pic"];
            NSString * picURL = [NSString stringWithFormat:@"%@%@",IMAGEHOSTURL,pic];
            
            imageView.frame = CGRectMake(i * self.advScrollView.frame.size.width, 0, self.advScrollView.frame.size.width, 140);
            imageView.contentMode = UIViewContentModeScaleAspectFill;
            imageView.clipsToBounds = YES;
            imageView.tag = i;
            imageView.userInteractionEnabled = YES;
            
            
            [imageView sd_setImageWithURL:[NSURL URLWithString:picURL] placeholderImage:nil];
            
            [self.advScrollView addSubview:imageView];
            
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(advAction:)];
            [imageView addGestureRecognizer:tap];
            
            VC.advImageLoadSuccess = YES;
        }
        
        if (self.advImageArray.count > 1) {
            //指示器
            [self.advPageControl removeFromSuperview];
            self.advPageControl = [[UIPageControl alloc] init];
            [self.baseScrollView addSubview:self.advPageControl];
            
            [self.advPageControl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(self.advScrollView.mas_centerX).offset(0);
                make.bottom.equalTo(self.advScrollView.mas_bottom).offset(5);
                make.width.equalTo(@100);
                make.height.equalTo(@30);
            }];
            
            self.advPageControl.numberOfPages = dataArr.count;
            self.advPageControl.currentPage = 0;
            [self.advPageControl addTarget:self action:@selector(pagecontrolChange:) forControlEvents:UIControlEventValueChanged];
            self.advPageControl.backgroundColor = [UIColor clearColor];
            
            self.advPageControl.pageIndicatorTintColor = [UIColor colorWithHexString:@"#a3e0ff"];
            self.advPageControl.currentPageIndicatorTintColor = [UIColor colorWithHexString:@"#66cbff"];
        }
        
        
        
        VC.pldImageView = nil;
        [VC.pldImageView removeFromSuperview];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        UIImage *image = [UIImage imageNamed:@"defaut_banner"];
        
        UIImageView *view = [[UIImageView alloc] initWithImage:image];
        
        view.frame = self.advScrollView.bounds;
        view.image = image;
        view.contentMode = UIViewContentModeScaleAspectFit;
        
        [view sd_setImageWithURL:[NSURL URLWithString:@"123"] placeholderImage:image];
        
        view.frame = self.advScrollView.bounds;
        
        [self.advScrollView addSubview:view];
        
        VC.pldImageView = nil;
        [VC.pldImageView removeFromSuperview];
        
    }];
    
}

- (void)getNewspaperData {
    
    NSMutableDictionary *paramDic = [[NSMutableDictionary alloc]init];
    
    [paramDic setObject:@"api_szb_readlist" forKey:@"method"];
    [paramDic setObject:gradersId forKey:@"gradersid"];
    [paramDic setObject:editionType forKey:@"editiontype"];
    
    [Utils getWithparameters:paramDic showHUD:NO success:^(NSInteger recode, id jsonObject) {
        
        NSDictionary *dic = (NSDictionary *)jsonObject;
        
        NSArray *arr = [dic objectForKey:@"re_data"];
        
        self.newspaperArr = [[NSMutableArray alloc]init];
        if (arr.count > 0) {

            for (NSDictionary *dict in arr) {
                
                SN_Readlist_Model *model = [SN_Readlist_Model mj_objectWithKeyValues:dict];
                
                [self.newspaperArr addObject:model];
            }
            
            
            emptyLable.hidden = YES;
        }else {
            emptyLable.hidden = NO;
        }
        
        self.readListTable.height = 158.5*self.newspaperArr.count;
        self.baseScrollView.contentSize = CGSizeMake(SCREENWIDTH, self.readListTable.bottom);
        
        [self.readListTable reloadData];
        [self.baseScrollView.mj_header endRefreshing];
        
        
    } failure:^(NSInteger recode, NSError *error) {
        
        [self.baseScrollView.mj_header endRefreshing];
        NSLog(@"%@",error.localizedDescription);
    }];
    
}

#pragma mark - SearchBarDelegate 
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    NSLog(@"搜索");
    SN_SearchViewController *searchVC = [[SN_SearchViewController alloc]init];
    searchVC.gradersId = gradersId;
    searchVC.editionType = editionType;
    searchVC.editionName = editionName;
    searchVC.gradersName = graderName;
    searchVC.searchType = 0;
    
    SYNavigationController *nav = [[SYNavigationController alloc]initWithRootViewController:searchVC];
    
    [self presentViewController:nav animated:YES completion:nil];
    return NO;
}

#pragma mark - TableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.sel_grader) {
        return self.graderArr.count;
    }else if (tableView == self.sel_edition) {
        return self.editionArr.count;
    }else if (tableView == self.readListTable) {
        return self.newspaperArr.count;
    }
    return 0;
    
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.readListTable) {
        SN_ReadListCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellIdentifier"];
        
        if (cell == nil) {
            cell = [[SN_ReadListCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cellIdentifier"];
            cell.delegate = self;
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        SN_Readlist_Model *listModel = [self.newspaperArr objectAtIndex:indexPath.row];
        
        [cell creatCell:listModel];
        
        return cell;
    }else if (tableView == self.sel_edition) {
        
        UITableViewCell *editionCell = [tableView dequeueReusableCellWithIdentifier:@"editionIdentifier"];
        
        if (editionCell == nil) {
            editionCell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"editionIdentifier"];
            
            editionCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        for (UIView *view in editionCell.contentView.subviews) {
            if (view.tag > 60) {
                [view removeFromSuperview];
            }
        }
        
        NSDictionary *dict = [self.editionArr objectAtIndex:indexPath.row];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH/2, 40)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.tag = 61;
        [titleLabel setTextColor:colorFromHex(@"#3b3b3b")];
        [titleLabel setFont:[UIFont systemFontOfSize:16]];
        [titleLabel setText:[dict objectForKey:@"editiontypename"]];
        [editionCell.contentView addSubview:titleLabel];
        
        if ([[dict objectForKey:@"editiontypename"] isEqualToString:defaultEdition]) {
            [titleLabel setTextColor:colorFromHex(@"#fb524a")];
            [editionCell setBackgroundColor:[UIColor whiteColor]];
        }else {
            UIView *line = [[UIView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2-0.5, 0, 0.5, 40)];
            [line setBackgroundColor:colorFromHex(@"#dedede")];
            line.tag = 62;
            [editionCell.contentView addSubview:line];
            [editionCell setBackgroundColor:colorFromHex(@"#f4f5f7")];
        }
        
        return editionCell;
        
    }else if (tableView == self.sel_grader) {
        
        UITableViewCell *graderCell = [tableView dequeueReusableCellWithIdentifier:@"graderIdentifier"];
        
        if (graderCell == nil) {
            graderCell = [[UITableViewCell alloc]initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"graderIdentifier"];
            graderCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        for (UIView *view in graderCell.contentView.subviews) {
            if (view.tag > 50) {
                [view removeFromSuperview];
            }
        }
        
        NSDictionary *dict = [self.graderArr objectAtIndex:indexPath.row];
        
        UILabel *titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH/2, 40)];
        titleLabel.textAlignment = NSTextAlignmentCenter;
        titleLabel.tag = 60;
        if ([[dict objectForKey:@"gradername"] isEqualToString:defaultGrader]) {
            [titleLabel setTextColor:colorFromHex(@"#fb524a")];
        }else {
            [titleLabel setTextColor:colorFromHex(@"#3b3b3b")];
        }
        
        if (defaultGrader == nil && indexPath.row == 0) {
            [titleLabel setTextColor:colorFromHex(@"#fb524a")];
        }
        
        [titleLabel setFont:[UIFont systemFontOfSize:16]];
        [titleLabel setText:[dict objectForKey:@"gradername"]];
        
        [graderCell.contentView addSubview:titleLabel];
        
        return graderCell;
    }
    
    return nil;
}

#pragma mark - TableViewDelegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (tableView == self.sel_edition) {

        if (defaultSelectedEditionIndex != indexPath.row) {
            defaultGrader = nil;
            [self.sel_grader reloadData];
        }
        defaultSelectedEditionIndex = indexPath.row;
        defaultEdition = [[self.editionArr objectAtIndex:indexPath.row] objectForKey:@"editiontypename"];;
        
        [self.sel_edition reloadData];
        
        
    }else if (tableView == self.sel_grader) {
        
        selectedEditionIndex = defaultSelectedEditionIndex;
        selectedGradeIndex = indexPath.row;
        gradersId = [NSString stringWithFormat:@"%@",[[self.graderArr objectAtIndex:indexPath.row] objectForKey:@"gradersid"]];
        editionType = [NSString stringWithFormat:@"%@",[[self.editionArr objectAtIndex:selectedEditionIndex] objectForKey:@"editiontypeid"]];
        graderName = [[self.graderArr objectAtIndex:indexPath.row] objectForKey:@"gradername"];
        editionName = [[self.editionArr objectAtIndex:selectedEditionIndex] objectForKey:@"editiontypename"];
        
        //储存到本地
        NSDictionary *imformation = [SyUserInfomation acquirePersonalImformationFromMemoryWithPersonID:USERID];
        NSMutableDictionary *informationM = [NSMutableDictionary dictionaryWithDictionary:imformation];
        
        [informationM setObject:gradersId forKey:@"grader"];
        [informationM setObject:editionType forKey:@"edtiontype"];
        [informationM setObject:editionName forKey:@"edtiontypename"];
        [informationM setObject:graderName forKey:@"gradername"];
        
        [SyUserInfomation personalImformationSaveWtih:informationM];
        
        //按钮内容
        NSString *subStr = [NSString stringWithFormat:@"%@ · %@",[[self.editionArr objectAtIndex:selectedEditionIndex] objectForKey:@"editiontypename"],[[self.graderArr objectAtIndex:indexPath.row] objectForKey:@"gradername"]];
        [self.subjectBtn setTitle:subStr forState:(UIControlStateNormal)];
        
        //刷新数据
        [self getNewspaperData];
        
        [self hideControl];
        
    }
}

#pragma mark - CellDelegate

- (void)chooseNewspaper:(SN_NewspaperModel *)paperModel {
    
    SN_NewspaperInfoViewController *infoVC = [[SN_NewspaperInfoViewController alloc]init];
    
    infoVC.paperModel = paperModel;
    
    [self.navigationController pushViewController:infoVC animated:YES];
    
}

- (void)moreNewspaper:(NSInteger)subjectId courseName:(NSString *)courseName{
    
    NSLog(@"%ld",subjectId);
    SN_QuestionReadMoreNews_Controller *vc = [[SN_QuestionReadMoreNews_Controller alloc] init];
    
    vc.courseIdStr = [NSString stringWithFormat:@"%ld",subjectId];
    vc.gradersIdStr = gradersId;
    vc.editionIdStr = editionType;
    vc.subjectTitle = courseName;
    vc.editionStr = [NSString stringWithFormat:@"%@%@",graderName,editionName];
    
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark - ScrollViewdelegate

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    if (scrollView == self.advScrollView) {
        
        [advImgtimer invalidate];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    if (scrollView == self.advScrollView) {
        
        advImgtimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(switchAdvImg) userInfo:nil repeats:YES];
        
    }
}

//pageControl的值改变
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    CGPoint point = scrollView.contentOffset;
    
    if (scrollView == self.advScrollView) {
        
        int page = point.x / SCREENWIDTH;
        
        if (page == self.advImageArray.count + 1) {
            
            scrollView.contentOffset = CGPointMake(SCREENWIDTH, 0);
            
            page = 0;
            
        }else if (page == 0){
            
            scrollView.contentOffset = CGPointMake(SCREENWIDTH * self.advImageArray.count, 0);
            page = (int)self.advImageArray.count - 1;
            
        }else{
            
            page--;
        }
        
        self.advPageControl.currentPage = page;
        
        
    }
    
}
//scrollView偏移
-(void)pagecontrolChange:(id)sender{
    
    CGPoint point = self.advScrollView.contentOffset;
    
    point.x = self.advPageControl.currentPage *SCREENWIDTH;
    
    [UIView animateWithDuration:0.4 animations:^{
        
        self.advScrollView.contentOffset = point;
    }];
    
}

#pragma mark - Get

- (UIScrollView *)baseScrollView {
    
    if (_baseScrollView == nil) {
        _baseScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH  - 49 - SafeAreaTopHeight-SafeAreaBottomHeight)];
        _baseScrollView.delegate = self;
        _baseScrollView.scrollEnabled = YES;
        _baseScrollView.showsHorizontalScrollIndicator = NO;
        _baseScrollView.showsVerticalScrollIndicator = NO;
        [_baseScrollView setBackgroundColor:[UIColor colorWithHexString:@"#ffffff"]];

        _baseScrollView.mj_header  = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            
            [self getNewspaperData];
        }];
    }
    
    return _baseScrollView;
}

- (UIScrollView *)advScrollView {
    if (_advScrollView == nil) {
        
        _advScrollView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 140)];
        _advScrollView.delegate = self;
        _advScrollView.scrollEnabled = YES;
        _advScrollView.showsHorizontalScrollIndicator = NO;
        _advScrollView.pagingEnabled = YES;
        [_advScrollView setBackgroundColor:[UIColor whiteColor]];
        
    }
    return _advScrollView;
}

- (UITableView *)readListTable {
    
    if (_readListTable == nil) {
        _readListTable = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 0) style:(UITableViewStylePlain)];
        _readListTable.delegate = self;
        _readListTable.dataSource = self;
        _readListTable.scrollEnabled = NO;
        _readListTable.separatorStyle = UITableViewCellSeparatorStyleNone;
        _readListTable.rowHeight = 158.5;
        [_readListTable setBackgroundColor:colorFromHex(@"ffffff")];
        
    }
    
    return _readListTable;
}

- (UIControl *)control {
    
    if (_control == nil) {
        
        _control = [[UIControl alloc] initWithFrame:CGRectMake(0, SafeAreaTopHeight, SCREENWIDTH, SCREENHEIGH-SafeAreaTopHeight-45)];
        _control.backgroundColor =[UIColor colorWithPatternImage:[UIImage imageNamed:@"control_bg"]];
        
        [_control addTarget:self action:@selector(hideControl) forControlEvents:UIControlEventTouchUpInside];
    }
    return _control;
}

- (UITableView *) sel_grader {
    
    if (_sel_grader==nil) {
        
        _sel_grader =[[UITableView alloc]initWithFrame:CGRectMake(SCREENWIDTH/2, 0, SCREENWIDTH/2, 360) style:UITableViewStylePlain];
        _sel_grader.delegate=self;
        _sel_grader.dataSource=self;
        _sel_grader.scrollEnabled = NO;
        _sel_grader.separatorStyle= UITableViewCellSeparatorStyleNone;
        _sel_grader.rowHeight = 40.0;
        
    }
    
    return _sel_grader;
}


- (UITableView *) sel_edition {
    
    if (_sel_edition==nil) {
        
        _sel_edition =[[UITableView alloc]initWithFrame:CGRectMake(0,0, SCREENWIDTH/2, 360) style:UITableViewStylePlain];
        _sel_edition.delegate=self;
        _sel_edition.dataSource=self;
        _sel_edition.scrollEnabled = NO;
        _sel_edition.rowHeight = 40.0;
        _sel_edition.separatorStyle= UITableViewCellSeparatorStyleNone;
        _sel_edition.backgroundColor=[UIColor colorWithHexString:@"f4f5f7"];
    }
    
    return _sel_edition;
}

- (UIButton *)subjectBtn {
    
    if (_subjectBtn == nil) {
        
        _subjectBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [_subjectBtn addTarget:self action:@selector(selectSubject) forControlEvents:(UIControlEventTouchUpInside)];
        [_subjectBtn setFrame:CGRectMake(15, SafeAreaTopHeight - 18 -13, 134, 18)];
        _subjectBtn.adjustsImageWhenHighlighted = NO;
        
        [_subjectBtn.titleLabel setFont:[UIFont systemFontOfSize:17]];
        [_subjectBtn setTitleColor:colorFromHex(@"#ffffff") forState:UIControlStateNormal];
        [_subjectBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, -40, 0, 0)];
        [_subjectBtn setImage:[UIImage imageNamed:@"choose_Down"] forState:(UIControlStateNormal)];
        [_subjectBtn setImage:[UIImage imageNamed:@"choose_Up"] forState:(UIControlStateSelected)];
        [_subjectBtn setImageEdgeInsets:UIEdgeInsetsMake(0, 112, 0, 0)];
        
        [self.navBar addSubview:_subjectBtn];
        
        
    }
    return _subjectBtn;
}

- (SNSearchBar *)snSearch {
    
    if (_snSearch == nil) {
        
        _snSearch = [[SNSearchBar alloc]initWithFrame:CGRectMake(self.subjectBtn.right, SafeAreaTopHeight - 8 - 28, SCREENWIDTH-30-10-self.subjectBtn.width, 28) leftImage:[UIImage imageNamed:@"search_Img"] placeholderColor:colorFromHex(@"fb524a")];
        _snSearch.hasCentredPlaceholder = NO;
        _snSearch.delegate = self;
        _snSearch.layer.cornerRadius = 4;
        _snSearch.layer.masksToBounds = YES;
        [_snSearch setPlaceholder:@"搜索"];
        [_snSearch setBackgroundColor:[UIColor whiteColor]];
        [_snSearch setBackgroundImage:[Utils imageWithColor:[UIColor clearColor] size:_snSearch.bounds.size]];
        [self.navBar addSubview:_snSearch];
        
        self.scanBtn = [UIButton buttonWithType:(UIButtonTypeCustom)];
        [self.scanBtn setFrame:CGRectMake(_snSearch.width - 28, 0, 28, 28)];
        [self.scanBtn addTarget:self action:@selector(scanAction) forControlEvents:(UIControlEventTouchUpInside)];
        [self.scanBtn setImage:[UIImage imageNamed:@"scanBtn"] forState:(UIControlStateNormal)];
        
        [_snSearch addSubview:self.scanBtn]; 
    }
    return _snSearch;
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    NSLog(@"----%@",event);
}

@end
